﻿using System;
using System.Collections.Generic;
using System.Data.Linq.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TracNghiemV1.Database;

namespace TracNghiemV1.DAO
{
    class SysUserDao
    {
        private static TestDataDataContext m_dataContext = null;

        public static IList<SYSUSER> GetSysUserList()
        {
            return DataContextDao.GetInstance().SYSUSERs.ToList();
        }

        public static void AddSysUser(SYSUSER newUser)
        {

            m_dataContext = DataContextDao.GetInstance();

            m_dataContext.SYSUSERs.InsertOnSubmit(newUser);
            m_dataContext.SubmitChanges();
        }

        public static void DeleteSysUser(string userId)
        {
            m_dataContext = DataContextDao.GetInstance();

            var user = m_dataContext.SYSUSERs.Single(u => u.USER_ID == userId);
            m_dataContext.SYSUSERs.DeleteOnSubmit(user);
            m_dataContext.SubmitChanges();
        }

        public static void ModifySysUser(SYSUSER modifiedUser)
        {
            m_dataContext = DataContextDao.GetInstance();

            var user = m_dataContext.SYSUSERs.Single(u => u.USER_ID == modifiedUser.USER_ID);

            user.USER_FIRST_NAME = modifiedUser.USER_FIRST_NAME;
            user.USER_LAST_NAME = modifiedUser.USER_LAST_NAME;
            user.USER_EMAIL = modifiedUser.USER_EMAIL;
            user.USER_MOBILE = modifiedUser.USER_MOBILE;
            user.USER_BIRTHDATE = modifiedUser.USER_BIRTHDATE;
            user.USER_ADDRESS = modifiedUser.USER_ADDRESS;

            m_dataContext.SubmitChanges();
        }

        public static SYSUSER FindSysUserWithUserId(string userId)
        {
            m_dataContext = DataContextDao.GetInstance();
            return m_dataContext.SYSUSERs.Single(u => u.USER_ID == userId);
        }

        public static SYSUSER FindSysUserWithUserIdAndPass(string userId, string password)
        {
            m_dataContext = DataContextDao.GetInstance();
            return m_dataContext.SYSUSERs.SingleOrDefault(u => u.USER_ID == userId && u.USER_ID == password);
        }

        public static IList<SYSUSER> FindSysUserListWithName(string name)
        {
            m_dataContext = DataContextDao.GetInstance();

            var users = from p in m_dataContext.SYSUSERs
                        where SqlMethods.Like(p.USER_FIRST_NAME, "%" + name + "%")
                        select p;
            return users.ToList();
        }

        public static int GetNumberOfTotalUser()
        {
            m_dataContext = DataContextDao.GetInstance();
            return m_dataContext.SYSUSERs.Count();
        }

        public static SYSUSER GetLatestUser()
        {
            m_dataContext = DataContextDao.GetInstance();
            return m_dataContext.SYSUSERs.ToList().Last();
        }
    }
}
